<?php

namespace plugin\admin\app\controller;

use app\services\PrizeDrawService;
use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Goods;
use plugin\admin\app\model\PrizeDrawGood;
use plugin\admin\app\model\UserPrizeDraw;
use support\Db;
use support\Request;
use support\Response;
use plugin\admin\app\model\PrizeDrawActivity;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 抽奖活动 
 */
class PrizeDrawActivityController extends Crud
{
    
    /**
     * @var PrizeDrawActivity
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new PrizeDrawActivity;
    }

    public function get(Request $request)
    {
        $activities = PrizeDrawActivity::all()->toArray();

        $data = [];
        foreach ($activities as $activity) {
            $data[] = [
                'name' => PrizeDrawActivity::buildTitle($activity),
                'value' => $activity['id']
            ];
        }
        return $this->json(0, '成功', $data);
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('prize-draw-activity/index');
    }

    public function open(Request $request)
    {
        Db::beginTransaction();
        try {
            PrizeDrawService::open($request->post('id'), true);

            Db::commit();
            return $this->json(0, '开奖成功');
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            Db::rollBack();
            return $this->json(400, $e->getMessage());
        }
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSupperAdmin() && $this->dataLimit) {
            if (!empty($data[$this->dataLimitField])) {
                $admin_id = $data[$this->dataLimitField];
                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        if ($data['start_time'] > $data['end_time']) {
            throw new BusinessException('开始时间不能大于结束时间');
        }

        $data['created_time'] = date('Y-m-d H:i:s');

        $activity = PrizeDrawActivity::orderBy('group_id', 'desc')->first();

        $groupId = 1;
        if ($activity) {
            $groupId = $activity['group_id'] + 1;
        }

        $data['group_id'] = $groupId;

        return $data;
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('prize-draw-activity/insert');
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        if ($data['start_time'] > $data['end_time']) {
            throw new BusinessException('开始时间不能大于结束时间');
        }

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('prize-draw-activity/update');
    }

    protected function doDelete(array $ids)
    {
        if (!$ids) {
            return;
        }

        if (UserPrizeDraw::whereIn('aid', $ids)->count() > 0) {
            throw new BusinessException('该活动有用户参与，不能删除');
        }

        $primary_key = $this->model->getKeyName();
        $this->model->whereIn($primary_key, $ids)->delete();

        PrizeDrawGood::whereIn('aid', $ids)->delete();

    }

    protected function formatNormal($items, $total): Response
    {
        $goodsId = array_column($items, 'pid');
        $goods = Goods::whereIn('id', $goodsId)->get()->keyBy('id')->toArray();

        foreach ($items as $key=>$item) {
            print_r($item);
            $items[$key]['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
            $items[$key]['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
            $items[$key]['goods_info'] = !empty($item['pid']) ? $goods[$item['pid']] : [];
            $items[$key]['status_text'] = PrizeDrawActivity::getStatusText($item['status']);
            $items[$key]['type_text'] = PrizeDrawActivity::getTypeText($item['type']);
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
